<?php
// $Id$

/**
 * Acct 封装来自 acct 数据表的记录及领域逻辑
 */
class Acct extends QDB_ActiveRecord_Abstract
{

    /**
     * 返回对象的定义
     *
     * @static
     *
     * @return array
     */
    static function __define()
    {
        return array
        (
            // 指定该 ActiveRecord 要使用的行为插件
            'behaviors' => '',

            // 指定行为插件的配置
            'behaviors_settings' => array
            (
                # '插件名' => array('选项' => 设置),
            ),

            // 用什么数据表保存对象
            'table_name' => 'acct',

            // 指定数据表记录字段与对象属性之间的映射关系
            // 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
            'props' => array
            (
                // 主键应该是只读，确保领域对象的“不变量”
                'id' => array('readonly' => true),
			//	'acctname'=>array('setter'=>'check_required'),
                'is_Onelevel'=>array('getter'=>'isOnelevel'),
            	'is_admin'=>array('getter'=>'isAdmin'),
            	'is_timeCardAdmin'=>array('getter'=>'istimeCardAdmin'),
            	
                /**
                 *  可以在此添加其他属性的设置
                 */
                # 'other_prop' => array('readonly' => true),
					//'rategroup_arrayinfo'=>array('getter'=>'get_rategroup_arrayinfo'),
                /**
                 * 添加对象间的关联
                 */
                # 'other' => array('has_one' => 'Class'),
				'parent'=>array('has_one'=>'acct','source_key'=>'agent_id','target_key'=>'id'),
            	'admin'=>array('has_one'=>'acct','source_key'=>'admin_id','target_key'=>'id'),
            	'rategroup'=>array('has_many'=>'rategroup','source_key'=>'id','target_key'=>'agent_id'),
				'sub'=>array('has_many'=>'acct','source_key'=>'id','target_key'=>'agent_id'),
                'a_gatewaygroup'=>array('has_one'=>'Getewaygroup','source_key'=>'gatewaygroupid','target_key'=>'id'),
            	'b_gatewaygroup'=>array('has_one'=>'Getewaygroup','source_key'=>'gatewaygroupid_acall','target_key'=>'id'),
				'a_rategroup'=>array('has_one'=>'rategroup','source_key'=>'rategroupid','target_key'=>'id'),
            	'b_rategroup'=>array('has_one'=>'rategroup','source_key'=>'rategroupid_acall','target_key'=>'id'),
            	'unionset'=>array('has_one'=>'acctextension','source_key'=>'id','target_key'=>'acctid'),
            	'web800'=>array('has_one'=>'web800','source_key'=>'id','target_key'=>'agent_id'),
            	'wapnews'=>array('has_many'=>'acctwapnews','source_key'=>'id','target_key'=>'acctid')	
            		),

            /**
             * 允许使用 mass-assignment 方式赋值的属性
             *
             * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
             */
            'attr_accessible' => '',

            /**
             * 拒绝使用 mass-assignment 方式赋值的属性
             */
            'attr_protected' => 'id',

            /**
             * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
             *
             * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
             */
            'create_reject' => 'createtime',

            /**
             * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
             */
            'update_reject' => 'createtime',

            /**
             * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
             *
             * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
             * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
             *
             * 如果填充值为一个数组，则假定为 callback 方法。
             */
            'create_autofill' => array
            (
                # 属性名 => 填充值
                # 'is_locked' => 0,
                'admin_id'=>self::cur_admin_id(),
            	//'smsurl'=>self::getAdminSmsurl(),
            	'agent_id' =>isset($_SESSION['acct']['id'])?$_SESSION['acct']['id']:0,
            	
            ),

            /**
             * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
             *
             * 填充值的指定规则同 create_autofill
             */
            'update_autofill' => array
            (
            ),

            /**
             * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
             *
             * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
             *
             * 如果需要添加一个自定义验证，应该写成
             *
             * 'title' => array(
             *        array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
             * )
             *
             * 然后在该类中添加 checkTitle() 方法。函数原型如下：
             *
             * static function checkTitle($title)
             *
             * 该方法返回 true 表示通过验证。
             */
            'validations' => array
            (
                'acctname' => array
                (
                    array('max_length', 30, '登陆账号不能超过 30 个字符'),
					//array(array(__CLASS__,'check_required'),'数据库中已经存在此用户名！')
                ),

                'password' => array
                (
                    array('max_length', 30, '明文密码不能超过 30 个字符'),

                ),

                'md5pass' => array
                (
                    array('max_length', 30, '登陆的md5密码不能超过 30 个字符'),

                ),

                'language' => array
                (
                    array('max_length', 30, '语言 all:多语言提示选择   cn:中文    en:英文不能超过 30 个字符'),

                ),

                'acclevel' => array
                (
                    array('is_int', '用户等级必须是一个整数'),

                ),

                'minute_len' => array
                (
                    array('is_int', '计费分钟长度，多少秒为一分钟显示在页面必须是一个整数'),

                ),

                'balance' => array
                (
                    array('is_float', '余额必须是一个浮点数'),

                ),

                'timepercent' => array
                (
                    array('is_float', '修正时间，是否按标准时间速度，主要用计费参数微调必须是一个浮点数'),

                ),

                'bcall_waitring' => array
                (
                    array('is_int', '是否加等待音乐,0不加，1加必须是一个整数'),

                ),

                'bcall_waitring_second' => array
                (
                    array('is_int', '等待的秒数必须是一个整数'),

                ),

                'cbinputcount' => array
                (
                    array('is_int', '回拨用户可输入的最大电话次数必须是一个整数'),

                ),

                'cbdtmfhangup' => array
                (
                    array('is_int', '是否按*号挂断 0否1是必须是一个整数'),

                ),

                'cbacall_bacll' => array
                (
                    array('is_int', '半直拨同时呼叫必须是一个整数'),

                ),

                'playtimelong' => array
                (
                    array('is_int', '是否报分钟数必须是一个整数'),

                ),

                'playwelecome' => array
                (
                    array('is_int', '是否报欢迎语必须是一个整数'),

                ),

                'costbalance' => array
                (
                    array('is_float', '已经消费金额必须是一个浮点数'),

                ),

                'prebalance' => array
                (
                    array('is_float', '帐户预存金额必须是一个浮点数'),

                ),

                'admin_id' => array
                (
                    array('is_int', '为1表示为代理用户，-1表示为管理用户必须是一个整数'),

                ),

                'agent_id' => array
                (
                    array('is_int', '上级代理ID必须是一个整数'),

                ),

                'callerid_type' => array
                (
                    array('is_int', '0 是否修改用户主叫号码  1 可以必须是一个整数'),

                ),

                'newuser_level' => array
                (
                    array('is_int', '0 是否建立新账号 1 可以自动建立必须是一个整数'),

                ),

                'newcard_level' => array
                (
                    array('is_int', '0 是否建立充值卡 1 可以自动建立必须是一个整数'),

                ),

                'downloaduser_level' => array
                (
                    array('is_int', '0 不导出帐号 1 可以导出帐号必须是一个整数'),

                ),

                'downloadcard_level' => array
                (
                    array('is_int', '0 不导出充值卡 1可以导出充值卡必须是一个整数'),

                ),

                'discharge_level' => array
                (
                    array('is_int', '1 按流量计费  0 按面值计费必须是一个整数'),

                ),

                'waitring_timelong' => array
                (
                    array('is_int', '输入被叫最大允许时间，默认为45秒以内必须是一个整数'),

                ),

                'update_level' => array
                (
                    array('is_int', '0 无批量修改权限 1 有批量修改权限必须是一个整数'),

                ),

                'addcitycode' => array
                (
                    array('is_int', '0 是否添加区号必须是一个整数'),

                ),

                'citycode' => array
                (
                    array('max_length', 255, '区号列表不能超过 255 个字符'),

                ),

                'trunk_playbanlce' => array
                (
                    array('is_int', '0 是否中继预约报余额必须是一个整数'),

                ),

                'callback_playbanlce' => array
                (
                    array('is_int', '0 是否回铃报余额必须是一个整数'),

                ),

                'billend_playbanlce' => array
                (
                    array('is_int', '0 通话结束报余额必须是一个整数'),

                ),

                'maxcall_timelong' => array
                (
                    array('is_int', '0 一次通话最大时长必须是一个整数'),

                ),

                'limitbindtel' => array
                (
                    array('is_int', '最大绑定电话个数必须是一个整数'),

                ),

                'agents_have' => array
                (
                    array('is_int', '是否有带理，1有，0无必须是一个整数'),

                ),

                'agent_prefix' => array
                (
                    array('max_length', 10, '所代理卡的前缀不能超过 10 个字符'),

                ),

                'rategroupid' => array
                (
                    array('is_int', '被叫费率组必须是一个整数'),

                ),

                'rategroupid_acall' => array
                (
                    array('is_int', '回铃费率组必须是一个整数'),

                ),

                'gatewaygroupid' => array
                (
                    array('is_int', '被叫中继组必须是一个整数'),

                ),

                'gatewaygroupid_acall' => array
                (
                    array('is_int', '回铃中断组必须是一个整数'),

                ),

                'lowbanlace' => array
                (
                    array('is_int', '余额是否不足，1正常，0欠费必须是一个整数'),

                ),

                'acallbillbalance' => array
                (
                    array('is_float', '超过回铃限制的扣费金额必须是一个浮点数'),

                ),

                'acallbillcount' => array
                (
                    array('is_int', '连续回铃接通几次不打电话就扣费 0不限制必须是一个整数'),

                ),

                'monthly_call_timelong' => array
                (
                    array('is_int', '每月允许时长多少，单位秒，0不做限制必须是一个整数'),

                ),

                'updatemonthly' => array
                (
                    array('is_int', '是否包月， 0 普通， 1是必须是一个整数'),

                ),

                'updateday' => array
                (
                    array('is_int', '是否包日， 0普通，1是必须是一个整数'),

                ),

                'updateyear' => array
                (
                    array('is_int', '是否包年 ，0普通，1是必须是一个整数'),

                ),

                'curmaxcall' => array
                (
                    array('is_int', '最大呼叫线数必须是一个整数'),

                ),

                'curcall' => array
                (
                    array('is_int', 'curcall必须是一个整数'),

                ),

                'batch_update' => array
                (
                    array('is_int', '批量修改用，1可以，0否必须是一个整数'),

                ),

                'enable' => array
                (
                    array('is_int', '是否被冻结，1正常，0，冻结帐号，不能使用登陆功能必须是一个整数'),

                ),

                'address' => array
                (
                    array('max_length', 255, '#联系地址不能超过 255 个字符'),

                ),

                'chinesename' => array
                (
                    array('max_length', 50, '#联系人中文名不能超过 50 个字符'),

                ),

                'tel' => array
                (
                    array('max_length', 30, '联系手机号码不能超过 30 个字符'),

                ),

                'email' => array
                (
                    array('max_length', 50, '联系的Email号码不能超过 50 个字符'),

                ),

                'overbalance' => array
                (
                    array('is_float', '透支金额必须是一个浮点数'),

                ),


            ),
        );
    }


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

    /**
     * 开启一个查询，查找符合条件的对象或对象集合
     *
     * @static
     *
     * @return QDB_Select
     */
    static function find()
    {
        $args = func_get_args();
        return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
    }

    /**
     * 返回当前 ActiveRecord 类的元数据对象
     *
     * @static
     *
     * @return QDB_ActiveRecord_Meta
     */
    static function meta()
    {
        return QDB_ActiveRecord_Meta::instance(__CLASS__);
    }


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
	static function _get_arrayinfo($rAppend = NULL)
	{
		$append = array();
		if (isset($_SESSION['acct']))
		{
			if ($_SESSION['acct']['admin_id'] == -1 && $_SESSION['acct']['agent_id'] == -1)
			{
			//为管理
				$append['admin_id'] = $_SESSION['acct']['id'];
			}else
			{
				$append['id'] = Acct::_get_have_acctid($_SESSION['acct']['id'], $_SESSION['acct']['admin_id']);
				$append['id'][] = $_SESSION['acct']['id'];
			}
		}
		$return = self::find($append)->order('id desc')->setColumns('id,acctname')->getAll()->toArray();
		
		return Helper_Array::toHashmap($return, 'id','acctname');
		
	}
	
	function get_rategroup_arrayinfo()
	{
		$rategroupArray = Rategroup::find(' agent_id = ?',isset($_SESSION['acct']['id'])?$_SESSION['acct']['id']:0)->setColumns('id,rategroupname')->asArray()->getAll();
		return Helper_Array::toHashmap($rategroupArray, 'id','rategroupname');
	}
	function _before_validate()
	{
		//if ()
		//dump($this);
	}
	 function check_required()
	{
	$args = (func_get_args());
	
	 if ($args[0] != $args[3][$args[1]])
	 {
	 	$required = self::find('id <> ? and acctname = ?',$args[3]['id'],$args[0])->getCount('id');
		
	 	if ($required)
		{
			$this->$args[1] = $args[3][$args[1]];
		}else {
			$this->$args[1] = $args[0];
		}
	 }
	}
	static function _getsubAcctHashMap()
	{
			
			
				$sub_agentArray = Acct::find(self::get_param())->setColumns('id,acctname')->asArray()->getAll();
				$sub_agentArray = Helper_Array::toHashmap($sub_agentArray, 'id','acctname');
				
				if ($_SESSION['acct']['acclevel'] == 2)
				{
				$sub_agentArray[$_SESSION['acct']['id']] = $_SESSION['acct']['acctname'];
				//$sub_agentArray = array_merge($sub_agentArray,array($_SESSION['acct']['id']=>$_SESSION['acct']['acctname']));
				
				}
		return $sub_agentArray;
		
				
	}
	static function _get_have_acctid($agent_id,$admin_id)
	{
		if ($_SESSION['acct']['acclevel'] == 0)
		{
			$reslut = self::find(' admin_id = ?',$_SESSION['acct']['id'])->setColumns('id')->asArray()->getAll();
			
			$reslut = Helper_Array::toHashmap($reslut, 'id','id');
			return array_values($reslut);
		}else
		{
		$rows = self::find(' agent_id = ? and  admin_id = ?',$agent_id,$admin_id)->setColumns('id')->getAll();
			$reslut = array();
			foreach ($rows as $k=>$v)
			{
				
				$item = array($v['id']);
				if (self::get_UserSub($v['id']))
				{
					$item = array_merge($item,self::_get_have_acctid($v['id'], $admin_id));
					//$item .= self::_get_have_acctid($v['id'], $admin_id);
				}
				$reslut = array_merge($reslut,$item);
				unset($item);
			}
		}
		return array_values($reslut);
	}
	static function get_UserSub($id)
	{
		$acct = self::find('agent_id = ?',intval($id))->setColumns('id')->getOne();
		if ($acct->id())
		{
		return true;
		}else
		{
		return false;
		}
	}
	
	/**
	 * 
	 * @access 获取当前用户的管理ID...
	 */
	static function cur_admin_id()
	{
		
	if (isset($_SESSION['acct']['admin_id']))
		{
			if ($_SESSION['acct']['admin_id'] == -1 && $_SESSION['acct']['agent_id'] == -1)
			{
			//为管理
				return $_SESSION['acct']['id'];
			}else
			{
				return $_SESSION['acct']['admin_id'];
			}
		}
	}
	static function get_param()
	{
		if (isset($_SESSION['acct']))
		{
			if ($_SESSION['acct']['admin_id'] == -1 && $_SESSION['acct']['agent_id'] == -1)
			{
			//为管理
				//$append['']
				$append['admin_id'] = $_SESSION['acct']['id'];
				
			}else
			{
				$append['admin_id'] = $_SESSION['acct']['admin_id'];
				$append['agent_id'] = Acct::_get_have_acctid($_SESSION['acct']['id'], $_SESSION['acct']['admin_id']);
				$append['agent_id'][] = $_SESSION['acct']['id'];
			}
		}
		return $append;
	}
	static function get_curId()
	{
		if (isset($_SESSION['acct']) )
		{
			if ($_SESSION['acct']['admin_id'] == -1 && $_SESSION['acct']['agent_id'] == -1)
			{
			//为管理
				return 0;
			}else
			{
				return $_SESSION['acct']['id'];
			}
		}else
		{
		return 0;
		}
	}
	static function make_card($acctid,$cardinfo)
	{
		$acct = self::find('id = ?',$acctid)->getOne();
		
		if (!$acct->id())
		{
			
		return false;
		}else if(!isset($cardinfo['balance'])){
			
			return false;
		}else if($acct->newcard_level == 0 && !$acct->admin_id == -1 && !$acct->agent_id == -1){
		
			return false;
		}else if ($acct->balance < $cardinfo['balance'] && $acct->discharge_level == 0 && !$acct->admin_id == -1 && !$acct->agent_id == -1)
		{
			
			return false;
		}else {
			try {
				$card = new Vouchercard($cardinfo);
				$card->save(0,'create');
				if (!$acct->admin_id == -1 && !$acct->agent_id == -1)
				{
				$acct->balance = $acct->balance - $card->balance;
				$acct->save(0,'update');
				}	
			return true;
			} catch (Exception $e) {
				
				return false;
			}
		
		}
		
	}
	static function timemoney($agent_id,$money)
	{
		$acct = self::find('id = ? and discharge_level = 1',$agent_id)->getOne();
		if (!$acct->id())
		{
			return '不存在此流量帐号';
		}
		if ($acct->parent->acclevel != 2)
		{
			return '只能2级一下代理才能直接增加金额';
		}
		try {
			#添加充值日志
			$log = new Voucherlog();
			//$acctuser = Acct::find('id = ?',$agent_id)->getOne();
			$log->acctname = isset($_SESSION['acct']['acctname'])?$_SESSION['acct']['acctname']:0;
			$log->admin_id = $acct->admin_id;
			$log->agent_id = $acct->id;
			$log->voucher_guid = '-1';
			$log->voucher_password = '-1';
			$log->voucher_balance = $money;
			$log->voucher_prebalance = $acct->balance;
			$log->voucher_acctname = $acct->acctname;
			$log->voucher_paylimitday = '-1';
			$log->save(0,'create');
			
			
			$acct->balance += $money;
			$acct->save(0,'update');
			return true;
		} catch (Exception $e) {
			return '充值失败';
		}
	}
	static function use_agentcardOnCW($agent_id,$cardname,$password)
	{
		$acctuser = self::find('id = ? and agent_id = admin_id and agent_id <> -1',$agent_id)->getOne();
		if (!$acctuser->id())
		{
			return false;
		}else
		{
		#1级
			
			$card = Agentcard::find('cardname = ? and password = ? and enable = 1 and vouchered = 0  ',$cardname,$password)->getOne();
				
			if (!($card->cardname))
			{
			return false;
		}else
		{
			try {
			//充值日志
			//Voucherlog::log($card, $acctuser);
					
				$acctuser->balance = $acctuser->balance + $card->balance;
				//$acctuser->voucherbalance += $card->balance;
				//$acctuser->expireddays += $card->expireddays;
				//$acctuser->expireddate = date('Y-m-d',strtotime("{$acctuser->expireddate} + {$card->expireddays} day"));
					
				$acctuser->save(0,'update');
				$card->vouchered = 1; //已经充值
				$card->voucher_acctname = $_SESSION['acct']['acctname'];
				$card->vouchereddate = date('Y-m-d');
				$card->vouchered_acctname=$acctuser->acctname;
				$card->save(0,'update');
					
				return true;
			} catch (Exception $e) {
			exit($e->getMessage());
			return false;
			}
			}
			}
	}
	static function use_agentcard($agent_id,$cardname,$password)
	{
	$acctuser = self::find('id = ? ',$agent_id)->getOne();
		if (!$acctuser->id())
		{
			return false;
		}else
		{
			#1级
			if($acctuser->is_Onelevel == true)
			{
				$whereAgentId = -1;
			}else{
				$whereAgentId = $acctuser->agent_id;
			}
			$card = Agentcard::find('cardname = ? and password = ? and enable = 1 and vouchered = 0 and agent_id = ? ',$cardname,$password,$whereAgentId)->getOne();
			
			if (!($card->cardname))
			{
				return false;
			}else
			{
				try {
					//充值日志
					//Voucherlog::log($card, $acctuser);
					$log = new Voucherlog();
					$log->acctname = isset($_SESSION['acct']['acctname'])?$_SESSION['acct']['acctname']:$acctuser->acctname;
					$log->admin_id = $acctuser->admin_id;
					$log->agent_id = $acctuser->id;
					$log->voucher_guid = $card->cardname;
					$log->voucher_password = $card->password;
					$log->voucher_balance = $card->balance;
					$log->voucher_prebalance = $acctuser->balance;
					$log->voucher_acctname = $acctuser->acctname;
					$log->voucher_paylimitday = '-1';
					$log->save(0,'create');
					
					$acctuser->balance = $acctuser->balance + $card->balance;
					//$acctuser->voucherbalance += $card->balance;
					//$acctuser->expireddays += $card->expireddays;
					//$acctuser->expireddate = date('Y-m-d',strtotime("{$acctuser->expireddate} + {$card->expireddays} day"));
					
					$acctuser->save(0,'update');
					$card->vouchered = 1; //已经充值
					$card->voucher_acctname = isset($_SESSION['acct']['acctname']) ? $_SESSION['acct']['acctname'] : $acctuser->acctname;
					$card->vouchereddate = date('Y-m-d');
					$card->vouchered_acctname=$acctuser->acctname;
					$card->save(0,'update');
					
					return true;
				} catch (Exception $e) {
					exit($e->getMessage());
					return false;
				}	
			}
		}
	}
	static function use_card($acctname,$cardname,$password)
	{
		$acctuser = self::find('acctname = ? or bindtel = ? ',$acctname,$acctname)->getOne();
		if (!$acctuser->id())
		{
			return false;
		}else
		{
			$card = Vouchercard::find('cardname = ? and password = ? and enable = 1 and vouchered = 0 and expireddate < CURRENT_DATE',$cardname,$password)->getOne();
			
			if (!($card->cardname))
			{
				return false;
			}else
			{
				try {
					//充值日志
					Voucherlog::log($card, $acctuser);
					
					$acctuser->balance = $acctuser->balance + $card->balance;
					$acctuser->voucherbalance += $card->balance;
					$acctuser->expireddays += $card->expireddays;
					$acctuser->expireddate = date('Y-m-d',strtotime("{$acctuser->expireddate} + {$card->expireddays} day"));
					
					$acctuser->save(0,'update');
					$card->vouchered = 1; //已经充值
					$card->vouchereddate = date('Y-m-d');
					$card->vouchered_acctname=$acctuser->acctname;
					$card->save(0,'update');
					
					return true;
				} catch (Exception $e) {
					return false;
				}	
			}
		}
	}
	static function make_agentcard($cardinfo)
	{
		$card = new Agentcard($cardinfo);
		$card->save(0,'create');
		return true;
	}
	static function getAcctUser()
	{
		$param = $_SESSION['acct']['acclevel'] == 2 ? 'agent_id': 'admin_id';
		$userCount = Acctuser::find($param.' = ?',$_SESSION['acct']['id'])->getCount('id');
		return $userCount;
	}
	
	static function check_user_pass($user_name,$user_pass)
	{
		
		if ($user_pass == '') return false;
		$user_obj = acct::find('acctname = ? and md5pass = ? and enable = 1',$user_name,md5($user_pass))->getOne();
		if ($user_obj->id()) {
			// 账户密码正确
			$_SESSION['acct'] = $user_obj->toArray();
			
			return true;
		}else{
			$user_obj = Acctuser::find('acctname = ? and password = ? and enable = 1',$user_name,($user_pass))->getOne();
			if($user_obj->id())
			{
			// 账户密码正确
			$_SESSION['acct'] = $user_obj->toArray();
			return true;
			}else{
			return false;
			}
		}
		//return false;
	}
	static function rm($agent_id,$admin_id)
	{
			$agent_id = intval($agent_id);
			$admin_id = intval($admin_id);
			$has_subid = Acct::_get_have_acctidTrue($agent_id, $admin_id);
			if (count($has_subid))
			{
				Acct::meta()->deleteWhere(array('id'=>$has_subid));
				Acctuser::meta()->deleteWhere(array('agent_id'=>$has_subid));
				Vouchercard::meta()->deleteWhere(array('agent_id'=>$has_subid));
				Rategroup::meta()->deleteWhere(array('agent_id'=>$has_subid));
				Acctwapset::meta()->deleteWhere(array('acctid'=>$has_subid));
			}
			
			Acctuser::meta()->deleteWhere('agent_id = '.$agent_id);
			Vouchercard::meta()->deleteWhere('agent_id = '.$agent_id);
			Rategroup::meta()->deleteWhere('agent_id = '.$agent_id);
			Acctwapset::meta()->deleteWhere('acctid = '.$agent_id);
	}
	
	static function _get_have_acctidTrue($agent_id,$admin_id)
	{
			$rows = self::find(' agent_id = ? and  admin_id = ?',$agent_id,$admin_id)->setColumns('id')->getAll();
			$reslut = array();
			foreach ($rows as $k=>$v)
			{
				$item = array($v['id']);
				if (self::get_UserSub($v['id']))
				{
					$item = array_merge($item,self::_get_have_acctidTrue($v['id'], $admin_id));
					//$item .= self::_get_have_acctid($v['id'], $admin_id);
				}
				$reslut = array_merge($reslut,$item);
				unset($item);
			}
		return array_values($reslut);
	}
	#是否是1级代理
	function isOnelevel()
	{
		
		if($this->admin_id == $this->agent_id && ($this->admin_id <> -1))
		{
			return true;
		}else{
			return false;
		}
	}
	#是否是管理
	function isAdmin()
	{
		if($this->acclevel == 0 && $this->agent_id == -1 && $this->admin_id == -1)
		{
			return true;
		}else{
			return false;
		}
	}
	function istimeCardAdmin()
	{
		
	}
	static function getacctName($id)
	{
		$acct = self::find('id = ?',$id)->setColumns('id,acctname')->getOne();
		if($acct->id())
		{
			return $acct->acctname;
		}else{
			return '';
		}
	}
	function getAcctSmsCount($startTime,$endTime)
	{
		$append['agent_id'] = Acct::_get_have_acctid($this->id, $this->admin_id);
		$append['agent_id'][] = $this->id;
		if($this->acclevel == 2)
		{
			$count = Smslog::find('agent_id = ? and admin_id = ? and created>= ? and created < ?',$this->id,$this->admin_id,$startTime,$endTime)->getCount('id');
		}else if($this->acclevel == 0){
			$count = Smslog::find('admin_id = ? and created>= ? and created < ?',$this->id,$startTime,$endTime)->getCount('id');
		}else{
			$count = 0;
		}
		
		return intval($count);
	}
	
	public static function getACCadminSmsBalance()
	{
		$acct = Acct::find('acclevel = 0')->setColumns('id,smsbalance')->getOne();
		return $acct->smsbalance;
	}
	
	public static function createDefaultRate($agent_id)
	{
		#呼出
		$rateGroup = new Rategroup();
		$rateGroup->rategroupname = '呼出费率组';
		
		$rateGroup->description = '呼出费率组';
		$rateGroup->save(0,'create');
		$rateGroup->agent_id = intval($agent_id);
		$rateGroup->save(0,'update');
		#回
		$rateGroup_call = new Rategroup();
		$rateGroup_call->rategroupname = '回铃费率组';
		
		$rateGroup_call->description = '回铃费率组';
		$rateGroup_call->save(0,'create');
		$rateGroup_call->agent_id = intval($agent_id);
		$rateGroup_call->save(0,'update');
		
		$rate_call = new Rate();
		$rate_call->prefix = '0';
		$rate_call->prefixname = '回铃固话费率';
		$rate_call->rateprice = 0;
		$rate_call->payunitsecond = 60;
		$rate_call->rategroupid = $rateGroup_call->id;
		$rate_call->agent_id = $agent_id;
		$rate_call->save(0,'create');
		
		$rate_call = new Rate();
		$rate_call->prefix = '1';
		$rate_call->prefixname = '回铃手机费率';
		$rate_call->rateprice = 0;
		$rate_call->payunitsecond = 60;
		$rate_call->rategroupid = $rateGroup_call->id;
		$rate_call->agent_id = $agent_id;
		$rate_call->save(0,'create');
		
		$rate_call = new Rate();
		$rate_call->prefix = '9';
		$rate_call->prefixname = '回铃VOIP费率';
		$rate_call->rateprice = 0;
		$rate_call->payunitsecond = 60;
		$rate_call->rategroupid = $rateGroup_call->id;
		$rate_call->agent_id = $agent_id;
		$rate_call->save(0,'create');
		######################
		$rate = new Rate();
		$rate->prefix = '0';
		$rate->prefixname = '回拨呼叫固话费率';
		$rate->rateprice = 0.1;
		$rate->payunitsecond = 60;
		$rate->rategroupid = $rateGroup->id;
		$rate->agent_id = $agent_id;
		$rate->save(0,'create');
		
		$rate = new Rate();
		$rate->prefix = '1';
		$rate->prefixname = '回拨呼叫手机费率';
		$rate->rateprice = 0.1;
		$rate->payunitsecond = 60;
		$rate->rategroupid = $rateGroup->id;
		$rate->agent_id = $agent_id;
		$rate->save(0,'create');
		
		$rate = new Rate();
		$rate->prefix = '9';
		$rate->prefixname = 'VOIP费率';
		$rate->rateprice = 0.1;
		$rate->payunitsecond = 60;
		$rate->rategroupid = $rateGroup->id;
		$rate->agent_id = $agent_id;
		$rate->save(0,'create');
		
		$rate = new Rate();
		$rate->prefix = '8';
		$rate->prefixname = 'VIP费率';
		$rate->rateprice = 0;
		$rate->payunitsecond = 60;
		$rate->rategroupid = $rateGroup->id;
		$rate->agent_id = $agent_id;
		$rate->save(0,'create');
	}
	static function getAdminSmsurl()
	{
		$admin = Acct::find('acclevel = 0')->getOne();
		if($admin->id())
		{
			return $admin->smsurl;
		}else{
			return '';
		}
	}
	function _after_create_post()
	{
		self::createDefaultRate($this->id);
	}
	
	
}


